Ext.define('appmod.controller.content.KMStartup', {
    extend: 'Ext.app.Controller',
    
   	stores:[
		'content.Tree',
		'content.BigView'
   	],   

    views: [
		'content.TreeDashboard',
		'content.Form'
    ],
	
    refs: [
		{ref: 'contentList', selector: 'content-list'},
		{ref:'contentFilev' , selector :'content-fileview'},
		{ref:'searchFormPanel' ,selector:'content-dashboard form'}
    ],	

    init: function() {
		var me = this;

    	me.control({

			'content-dashboard button[action=find]' : {
				click: {
					fn:me.searchAndPageProduct,
					scope:me
				}
			},			
			'content-list menuitem[action=showProductAddingForm]': {
				click:{
					fn:me.showProductAddingForm,
					scope:me
				}
			},
			'content-list menuitem[action=showProductEditingForm]': {
				click:{
					fn:me.showProductEditingForm,
					scope:me
				}
			},
			'content-list menuitem[action=deleteProducts]': {
				click:{
					fn:me.showDelProductsDialog,
					scope:me
				}
			}											
    	});
    },

	
	/**
	 * load main compont in this controller to framework container
	 */
	loadInitComp : function() {
		var mainPanel = Ext.create('appmod.view.content.TreeDashboard' , {
			region : 'center',
			border:false,
			padding:'0 0 0 0'
		});
		return mainPanel;		
	},
	

	// --- use this app lication
	onLaunch:function(app) {
		var me = this;
		
		// --- binding store --
		var dsBigView = me.getContentBigViewStore();
		var contentFilev = me.getContentFilev();
		contentFilev.bindStore( dsBigView );
		
		dsBigView.load();



	},

	resetProductForm:function(btn, event, eOpts) { 
		var upWin = eOpts.window;                   
		                                            
		var formPanel = upWin.down('product-form'); 
                                                    
		var form = formPanel.getForm();             
		form.reset();		                        
	},                                              

	searchAndPageProduct:function(btn, event, eOpts) {
		
		var me = this;

		var searchFormPanel = me.getSearchFormPanel();

		var searchForm = searchFormPanel.getForm();
		var formFields = searchForm.getValues();
		var reqParams = {};
		for (var i in formFields) {
			if (formFields[i] != '') {
				reqParams[i] = formFields[i];
			}
		}
		var dsPageProds = me.getProductPagingStore();
		var pageReqProxy = dsPageProds.getProxy();
		pageReqProxy.extraParams = reqParams;
		dsPageProds.loadPage(1);
	},
	showProductAddingForm:function() {
		var me = this;
		var win = null;
		// --- get select form ---
		var listView =  me.getProductList();	         
		var selModel = listView.getSelectionModel();     
		var recs = selModel.getSelection();                 
		if (recs.length  > 1) {                           
			Ext.MessageBox.show({                        
        		title: "提示",                             
        		msg: '只能选择一条媒体数据',                       
        		buttons: Ext.MessageBox.OK,              
        		icon: Ext.MessageBox.WARNING             
       		});
			return ;                                     
		}
		
		// --- create parent store ---
		var dsProdTree = me.getProductTreeStore();
		dsProdTree.load();
	
		var fieldStores = {
			'dsParentCatelog' : dsProdTree
		};
		
		// --- build new form ---
		if (!win) {
			win = new Ext.create('widget.window', {
				title : '媒 体',
				closable : true,
				width : 250,
				height : 210,
				modal:true,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					fieldStores:fieldStores,
					defaults: {
        				labelWidth:65
    				},
					xtype : 'product.form',
					region:'center'
				}],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
            				text: '保 存',
							action:'addProduct'
        				},{
            				text: '清 空 ',
							action:'reset'
        				}
				    ]
				}]	
			});
		}
		
		// --- find form ---
		var form = win.down("product-form");
		
		if (recs && recs.length == 1) {
			// --- reset parent id ---
			var ffParentId = form.down('treecombo[name=parentId]');
			ffParentId.setValue(recs[0].getId());
		}
		
		var saveBtn = win.down('button[action="addProduct"]');
		saveBtn.on("click",me.saveAddProduct , me , {
			window : win
		});

		var resetBtn = win.down('button[action="reset"]');
		resetBtn.on("click",me.resetProductForm , me , {            
			window : win                                             
		});                                                          

		if ( !win.isVisible() ) {
			win.show();
		}		
	},
	
	saveAddProduct:function(btn, event, eOpts) { 
		var me = this;

		var upWin = eOpts.window;
		
		var formPanel = upWin.down('product-form');

		var form = formPanel.getForm();
		
		// --- get list panel and reflash ---
		var prodList = me.getProductList();

		form.submit({
			url:'../../data/resource/product/submit_addproduct.json',
			success:function(form , action) {
				 Ext.Msg.alert('成功', action.result.msg);
				 if (upWin.isVisible()){
				 	upWin.close();
				 }
				 var store = prodList.getStore();
				 if (store) {
				 	store.load();
				 }
				 
			},
			failure: function(from, action){
				switch (action.failureType) {
					case Ext.form.action.Action.CLIENT_INVALID:
						Ext.Msg.alert('失败', '表单里包含错误的信息');
						break;
					case Ext.form.action.Action.CONNECT_FAILURE:
						Ext.Msg.alert('失败', '服务器连接失败,请联系管理人员');
						break;
					case Ext.form.action.Action.SERVER_INVALID:
						Ext.Msg.alert('失败', action.result.msg);
				}
			}
		});		
	},
	
	showProductEditingForm:function() {
		me = this;
		var win = null;

		var listView =  me.getProductList();	         
		var selModel = listView.getSelectionModel();     
		var rec = selModel.getSelection();               
                                                         
		if (rec.length == 0) {                           
			Ext.MessageBox.show({                        
        		title: "提示",                             
        		msg: '请先选择一条媒体数据',                       
        		buttons: Ext.MessageBox.OK,              
        		icon: Ext.MessageBox.WARNING             
       		});                                          
			return ;                                     
		} else if (rec.length  > 1) {                    
			Ext.MessageBox.show({                        
        		title: "提示",                             
        		msg: '只能选择一条媒体数据',                       
        		buttons: Ext.MessageBox.OK,              
        		icon: Ext.MessageBox.WARNING             
       		});                                          
			return ;                                     
		}                                                
                                                     
		var dsProdTree = me.getProductTreeStore();
		dsProdTree.load();
	
		var fieldStores = {
			'dsParentCatelog' : dsProdTree
		};
		
		// --- build new form ---
		if (!win) {
			win = new Ext.create('widget.window', {
				title : '媒 体',
				closable : true,
				width : 250,
				height : 210,
				modal:true,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					fieldStores:fieldStores,
					defaults: {
        				labelWidth:65
    				},
					xtype : 'product.form',
					region:'center'
				}],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
            				text: '保 存',
							action:'editProduct'
        				},{
            				text: '清 空 ',
							action:'reset'
        				}
				    ]
				}]	
			});
		}
		
		// --- find form ---
		var formPanel = win.down("product-form");
		
		// --- init form data ---                                       
		var form = formPanel.getForm();                                 
		                                                                
		form.load({                                                     
			params:{                                                    
				id:rec[0].getId()                               
			},                                                          
			url: '../../data/resource/product/load_product.json',      
            waitMsg: '数据加载中'			                                
		});                                                             
		                                                                
                                                                        
		var submitBtn = win.down('button[action="editProduct"]');
		submitBtn.on("click",me.submitEditProduct , me , {             
			window: win                                                 
		});                                                             
	                                                                    
		var resetBtn = win.down('button[action="reset"]');   
		resetBtn.on("click",me.resetProductForm , me , {               
			window : win                                                
		});                                                             
				                                                        


		if ( !win.isVisible() ) {
			win.show();
		}			
	},
	
	                                                                        
	submitEditProduct:function(btn, event, eOpts) {                        
		var me = this;                                                      
                                                                            
		var upWin = eOpts.window;                                           
		                                                                    
		var formPanel = upWin.down('product-form');                         
                                                                            
		var form = formPanel.getForm();                                     
		                                                                    
		// --- get list panel and reflash ---                               
		var prodList = me.getProductList();                         
                                                                            
		form.submit({                                                       
			url:'../../data/resource/product/submit_updateproduct.json',    
			success:function(form , action) {                               
				 Ext.Msg.alert('成功', action.result.msg);                    
				 if (upWin.isVisible()) {                                   
				 	upWin.close();                                          
				 }                                                          
				                                                            
				 var store = prodList.getStore();                       
				 if (store) {                                               
				 	store.load();                                           
				 }                                                          
				                                                            
			},                                                              
			failure: function(from, action){                                
				switch (action.failureType) {                               
					case Ext.form.action.Action.CLIENT_INVALID:             
						Ext.Msg.alert('失败', '表单里包含错误的信息');                  
						break;                                              
					case Ext.form.action.Action.CONNECT_FAILURE:            
						Ext.Msg.alert('失败', '服务器连接失败,请联系管理人员');             
						break;                                              
					case Ext.form.action.Action.SERVER_INVALID:             
						Ext.Msg.alert('失败', action.result.msg);             
				}                                                           
			}                                                               
		});                                                                 
	} ,
	
	showDelProductsDialog:function(item, eventObj, eOpts) {
		var me = this;

		// --- get contact person id ---
		var prodList =  me.getProductList();	
		var cpSelModel = prodList.getSelectionModel();
		var recs = cpSelModel.getSelection();		
		if (recs.length == 0) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '请先选择媒体',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		} 		

		
		// --- select resource --
		var removeRecs = "";
		for (var i = 0 ; i < recs.length ; i++) {
			if (removeRecs.length != 0 ) {
				removeRecs += ",";
			}
			removeRecs += recs[i].get('text');
		}
		Ext.MessageBox.confirm('确认', '确定要删除媒体: "'+removeRecs+'"?',me.confirmDelProducts , me);			},
	confirmDelProducts:function(confirm) {
		var me = this;
		
		var listView =  me.getProductList();	
		var selModel = listView.getSelectionModel();
		var rec = selModel.getSelection();
		
		if (confirm == "no") {
			return;
		}


		var jsonObj = [];
		for (var i = 0 ; i < rec.length ; i++) {
			jsonObj.push(rec[i].getId());
		}

		
		// --- update record using ajax
		try {

			Ext.Ajax.request({
				url: '../../data/resource/product/submit_deleteproducts.json',
				method:'post',
				jsonData:jsonObj,
				success: function(response, opts) {

					var listView = me.getProductList();
					// --- update load ---
					listView.getStore().load();
										 
     				var obj = Ext.decode(response.responseText);
					 
					 // --- popup message ---
					Ext.MessageBox.show({
        				title: "提示",
        				msg: obj.msg,
        				buttons: Ext.MessageBox.OK,
        				icon: Ext.MessageBox.WARNING
       				});
					
					// --- reload ---

				},
				failure: function(response, opts) {
					alert("error alert for deleting provider contact person!");
		
				}
			});

			
		} catch (e) {
			Ext.log({
				msg:'error : ' + e
			})
		}			
	}                                                                     
	                                                                        	
	
	
		
});